package com.demo.netty.handler;

import com.demo.netty.protocol.CustomProtocol;
import com.demo.netty.util.NettySocketHolder;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

/**
 * @author liangliang
 */
@ChannelHandler.Sharable
public class NettyServerHandler extends SimpleChannelInboundHandler<CustomProtocol> {

    @Override
    public void channelRead0(ChannelHandlerContext ctx, CustomProtocol customProtocol) {

        System.out.println("收到CustomProtocol{}："+customProtocol);

        // 保存客户端与Channel之间的联系
        NettySocketHolder.put(customProtocol.getId(),(NioSocketChannel)ctx.channel());

    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
            .addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
